package cn.com.youjile.coding;

import cn.com.youjile.entity.MsgInfo;
import cn.com.youjile.utils.JsonUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * @Author youjile
 * @CreateDate 2021/3/12
 * @Describe 自定义编码器
 */
public class GeneralEncoder extends MessageToByteEncoder {

    private static final Logger logger = LoggerFactory.getLogger(GeneralEncoder.class);

    private int headerLength = 6;

    public GeneralEncoder(){

    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        logger.debug("ctx = [" + ctx + "], msg = [" + msg + "], out = [" + out + "]");
        if(msg instanceof MsgInfo) {
            MsgInfo msgInfo = (MsgInfo)msg;
            byte[] bytes = msgInfo.getInfo();
            int dataType = msgInfo.getCode();
            byte[] tmp = new byte[headerLength];
            int length = bytes.length;
            //写入body长度
            tmp[0] = (byte)(length & 0xff);
            tmp[1] = (byte)((length>>8) & 0xff);
            tmp[2] = (byte)((length>>16) & 0xff);
            tmp[3] = (byte)((length>>24) & 0xff);
            //写入数据类型
            tmp[4] = (byte)(dataType & 0xff);
            tmp[5] = (byte)((dataType>>8) & 0xff);
            //写入数据
            out.writeBytes(tmp);
            out.writeBytes(bytes);
        }

    }


}
